
let userId_const = localStorage.getItem("userId");
let userName_const = localStorage.getItem("userName");
let username = $(".dropdown-user-name");
username.find('i').remove();
let user_name = '<i>你好，'+userName_const+'老师</i>';
username.append(user_name);                       //生成导航栏的老师名字
username = $("#user_name");
username.find('span').remove();
user_name = '<span>'+userName_const+'老师</span>'      //生成导航栏下拉框的老师名字
username.append(user_name);

let courseId_arr = localStorage.getItem("courseId");
let courseName_arr = localStorage.getItem("courseName");

//获取url中的参数方法
function getUrlParam(name) {
    //构造一个含有目标参数的正则表达式对象
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    //匹配目标参数
    let r = window.location.search.substr(1).match(reg);
    //返回参数
    if (r != null) {
        return unescape(r[2]);
    } else {
        return null;
    }
}

var courseId = getUrlParam("courseId");
var target_numArr = []; // 定义一个环节关键词空数组
var target_content = [];//定义一个环节详细内容空数组
var eva_numArr = []; // 定义一个评价关键词空数组
var eva_content = [];//定义一个评价详细内容空数组
var index;//元素索引值
var target_length;//课程目标数量
//多个文本框数据合并传入数据库
function Total() {
    target_numArr = [];
    eva_numArr = [];
    let txt1 = $("#procedure").find(":text"); // 获取所有文本框
    let txt2 = $("#evaluate").find(":text");
    for (let i = 0; i < txt1.length; i++) {
        target_numArr.push(txt1.eq(i).val()); // 将文本框的值添加到数组中

    }
    for (let i = 0; i < txt2.length; i++) {
        eva_numArr.push(txt2.eq(i).val());
    }
}

//模态框内容保存
$(function () {
    $("#content-submit").click(function () {
        target_content[index] = $("#myModal").find("textarea").val();
        console.log(target_content);
    })
    $("#eva-content-submit").click(function () {
        eva_content[index] = $("#myEvaModal").find("textarea").val();
        console.log(eva_content);
    })
})

//获取文本框的值到模态框标题
$(function () {
    $("#myModal,#myEvaModal").on('shown.bs.modal', function () {
        $("#myModal,#myEvaModal").find("textarea").focus();
    })
    let target = $(".target");
    let evaluation = $(".evaluation");
    target.on("click", "a", function () {
        index = parseInt($(this).index() / 3);// 详细安排按钮索引值
        let txt = $("#procedure").find(':text'); // 获取所有文本框
        if (txt.eq(index).val().match(/^[ ]*$/)) {
            swal({title:"请先填写关键词",type:"warning"});
        } else {
            $(".target a").attr("data-target", "#myModal");
            $("#myModalLabel").find('span').remove();
            $("#myModalLabel").append('<span>' + txt.eq(index).val() + '</span>');
            $("#myModal").on('hidden.bs.modal', function () {
                $(".target a").removeAttr("data-target");
            })
        }
    });
    evaluation.on("click", "a", function () {
        index = parseInt($(this).index() / 3);// 评价方式按钮索引值
        let txt = $("#evaluate").find(':text'); // 获取所有文本框
        if (txt.eq(index).val().match(/^[ ]*$/)) {
            swal({title:"请先填写关键词",type:"warning"});
        } else {
            $(".evaluation a").attr("data-target", "#myEvaModal");
            $("#myEvaModalLabel").find('span').remove();
            $("#myEvaModalLabel").append('<span>' + txt.eq(index).val() + '</span>');
            $("#myEvaModal").on('hidden.bs.modal', function () {
                $(".evaluation a").removeAttr("data-target");
            })
        }
    });

    //删除某个教学环节
    target.on("click", "button", function () {
        index = parseInt($(this).index() / 3);// 删除按钮索引值
        console.log(index);
        target.find("input").eq(index).remove();
        target.find("a").eq(index).remove();
        target.find("button").eq(index).remove();
        for (var i = index; i < target_content.length; i++)
            target_content[i] = target_content[i + 1];
    });
    //删除某个评价方式
    evaluation.on("click", "button", function () {
        index = parseInt($(this).index() / 3);// 删除按钮索引值
        console.log(index);
        evaluation.find("input").eq(index).remove();
        evaluation.find("a").eq(index).remove();
        evaluation.find("button").eq(index).remove();
        for (var i = index; i < eva_content.length; i++)
            eva_content[i] = eva_content[i + 1];
    });
})


//鼠标悬停显示详细内容
$(function () {
    $(".target").on("mouseover", "a", function () {
        index = parseInt($(this).index() / 3);
        $(".target").find("a").eq(index).attr("title", target_content[index]);
    });
    $(".evaluation").on("mouseover", "a", function () {
        index = parseInt($(this).index() / 3);
        $(".evaluation").find("a").eq(index).attr("title", eva_content[index]);
    });
    $(".target .evaluation").on("mouseout", "a", function () {
        index = parseInt($(this).index() / 3);
        $(".target .evaluation").find("a").eq(index).removeAttr("title");
    });

})


//添加新输入框
$(function () {
    $("#add1").on('click', function () {
        let add = '<input type="text" class="form-control target-input" data-toggle="tooltip" data-placement="bottom" placeholder="教学环节" required="required"> <a href="#" data-toggle="modal" >详细安排</a> <button class="btn-xs btn-danger"> 删除 </button>'
        $(".target").append(add);
    })
    $("#add2").on('click', function () {
        let add = '<input type="text" class="form-control target-input" data-toggle="tooltip" data-placement="bottom" placeholder="评价方式" required="required"> <a href="#" data-toggle="modal" >详细安排</a> <button class="btn-xs btn-danger"> 删除 </button>'
        $(".evaluation").append(add);
    })
});

function check() {
    var trcontent = "";
    $("#course-target tr").each(function () {
        $(this).children("td").each(function () {
            var checkbox = $(this).find(':checkbox:checked');
            if (checkbox.length > 0) {
                checkbox.each(function (i) {
                    //各个课程目标教学环节
                    var zx = $(checkbox[i]).val();
                    trcontent = trcontent + zx + "&";
                });
                //各个课程目标评价方式
                trcontent = trcontent.substring(0, trcontent.length - 1);
                trcontent = trcontent + "|";
            }
        });
        //所有课程目标整合
        trcontent = trcontent.substring(0, trcontent.length - 1);
        trcontent = trcontent + ";";
    });
    trcontent = trcontent.substring(0, trcontent.length - 1);
    console.log(trcontent);
    var content = trcontent.split(";");
    var empty = true;
    for (let i = 1; i <= content.length; i++) {
        let target_content = content[i - 1].split("|");
        if (!target_content[0] || !target_content[1] || content.length < target_length) {
            empty = false;
        }
    }
    if (!empty) {
        swal({title:"教学环节和评价方式均不能为空！",type:"warning"});
        return;
    }
    //判断评价权值是否符合规范
    let total = 0;
    let totalstr = '';
    $("#course-target tr").each(function () {
        $(this).children("td").each(function () {
            var num = $(this).find('input:text');
            num.each(function (i) {
                var value = $(num[i]).val();
                if (value) {
                    total = total + parseInt(value);
                }
                totalstr = totalstr + value + ';';
            })
        });
        totalstr = totalstr.substring(0, totalstr.length - 1);
        totalstr = totalstr + "|";
    });
    totalstr = totalstr.substring(0, totalstr.length - 1);
    let total_arr = totalstr.split('|');
    if (total != 100) {
        swal({title:"总权值需等于100，请注意检查！",type:"warning"});
        return;
    }
    for (let i = 1; i <= content.length; i++) {
        let target_content = content[i - 1].split("|");
        //更新表格数据
        $.ajax({
            url: '/target/updateTeacheWayById',
            type: 'post',
            dataType: 'json',
            data: {
                "courseId": courseId,
                "courseTargetNum": i,
                "teacheWay": target_content[0],
                "evaluationWay": target_content[1],
                "evaluationValue": total_arr[i - 1]
            },
            success: function () {
                //findById();
            }
        });
    }
    swal({title:"提交成功！",type:"success"});
}

//显示表格数据
function findById() {
    let flag=false;
    let procedure_keywords_input = '';//设初始值
    let evaluation_keywords_input = '';//设初始值
    let courseId_arr_handle;
    courseId_arr_handle = courseId_arr.split(",")//分割数据
    for(let i=0;i<courseId_arr_handle.length;i++){
        if(courseId==courseId_arr_handle[i]){
            flag=true;
        }
    }
    if(flag==true){
        $.ajax({
            url: '/method/findById',
            type: 'get',
            dataType: 'json',
            async:false,
            data: {"courseId": courseId},
            success: function (data) {
                //获取课程名
                $.ajax({
                    url: '/lv_course/findNameById',
                    type: 'get',
                    dataType: 'json',
                    async:false,
                    data:{"courseId":courseId},
                    success: function (data) {
                        courseName=data.courseName;
                    }
                });
                $("#courseName").empty();
                $("#courseName").append(courseName);

                let procedure_result;//教学环节关键词
                let evaluation_result;//评价方式关键词
                let procedure_content=[];//教学环节详细内容
                let evaluation_content=[];//评价方式详细内容
                let selected_procedure_result;//已选教学环节关键词
                let selected_evaluation_result;//已选评价方式关键词
                let selected_evaluation_value;//已选评价方式权值

                $.ajax({
                    url: '/target/findTargetContent',
                    type: 'get',
                    dataType: 'json',
                    async:false,
                    data: {"courseId": courseId},
                    success:function (data){
                        for(let i in data){
                            procedure_content.push(data[i].courseTargetContent);
                        }
                    }
                });
                $.ajax({
                    url: '/target/findEvaluationContent',
                    type: 'get',
                    dataType: 'json',
                    async:false,
                    data: {"courseId": courseId},
                    success:function (data){
                        for(let i in data){
                            evaluation_content.push(data[i].courseEvaluationContent);
                        }
                    }
                });
                procedure_result = data.teacheWay.split(",");//分割数据
                evaluation_result = data.evaluaKeywords.split(",");//分割数据

                $.ajax({
                    url: '/target/findTargetAllById',
                    type: 'get',
                    dataType: 'json',
                    data: {"courseId": courseId},
                    success: function (data) {
                        //查询课程目标内容
                        target_length = data.length;
                        $("#course-target").find('tr').remove();
                        let tr;
                        for (let i in data) {
                            if(data[i].teacheWay)
                                selected_procedure_result = data[i].teacheWay.split("&");//分割数据
                            if(data[i].evaluationWay)
                                selected_evaluation_result = data[i].evaluationWay.split("&");//分割数据
                            if(data[i].evaluationValue)
                                selected_evaluation_value = data[i].evaluationValue.split(";")//分割数据

                            console.log("selected_evaluation_result="+selected_evaluation_result);
                            let procedure_keywords = '';//清空上一教学环节关键词
                            let evaluation_keywords = '';//清空上一评价方式关键词
                            let evaluation_value = '';//清空上一评价方式权值
                            let j = 0, l = 0;

                            //生成关键词复选框
                            for (let k in procedure_result) {
                                if (selected_procedure_result[j] === procedure_result[k]) {
                                    procedure_keywords += '<label><input type="checkbox" checked value="' + procedure_result[k] + '"/>' + procedure_result[k] + '</label><br>';
                                    j++;
                                } else {
                                    procedure_keywords += '<label><input type="checkbox" value="' + procedure_result[k] + '"/>' + procedure_result[k] + '</label><br>';
                                }
                            }
                            for (let k in evaluation_result) {
                                if (selected_evaluation_result[l] === evaluation_result[k]) {
                                    evaluation_keywords += '<label><input type="checkbox" checked value="' + evaluation_result[k] + '"/>' + evaluation_result[k] + '</label><br>';
                                    evaluation_value += '<label>' + evaluation_result[k] + ':<input type="text" oninput="value=value.replace(/[^\\d]/g,\'\');if(value>100)value=100;if(value<0)value=null" value="' + selected_evaluation_value[k] + '"/></label><br>'
                                    l++;
                                } else {
                                    evaluation_keywords += '<label><input type="checkbox" value="' + evaluation_result[k] + '"/>' + evaluation_result[k] + '</label><br>';
                                    //生成评价方式权值输入框
                                    evaluation_value += '<label>' + evaluation_result[k] + ':<input type="text" oninput="value=value.replace(/[^\\d]/g,\'\');if(value>100)value=100;if(value<0)value=null" disabled/></label><br>'
                                }
                            }
                            tr = '<td>' + data[i].courseTargetContent + '</td>'
                                + '<td>' + procedure_keywords + '</td>'
                                + '<td class="evaluation_keywords">' + evaluation_keywords + '</td>'
                                + '<td>' + evaluation_value + '</td>'
                            $("#course-target").append('<tr>' + tr + '</tr>');
                        }

                        //通过复选框控制文本框
                        var s = $("#course-target .evaluation_keywords").find("input:checkbox");
                        s.each(function (i) {
                            $(this).click(function () {
                                if ($(this).is(':checked')) {
                                    $(this).parent().parent().next().find("input:text").eq(i % (evaluation_result.length)).removeAttr("disabled");
                                }
                                if (!$(this).is(':checked')) {
                                    $(this).parent().parent().next().find("input:text").eq(i % (evaluation_result.length)).attr("disabled", "true").val('');
                                }
                            });
                        });

                    }
                });
                //若数据库中已存在关键词，则输出到输入框中
                for (let i in procedure_result) {
                    procedure_keywords_input += '<input type="text" class="form-control target-input" data-toggle="tooltip" data-placement="bottom" value="' + procedure_result[i] + '"' + 'title="' + procedure_result[i] + '"' +
                        ' required="required"/> <a href="#" data-toggle="modal" data-placement="bottom"> 详细安排 </a> <button class="btn-xs btn-danger"> 删除 </button>'
                }

                for (let i in evaluation_result) {
                    evaluation_keywords_input += '<input type="text" class="form-control target-input" data-toggle="tooltip" data-placement="bottom" value="' + evaluation_result[i] + '"' + 'title="' + evaluation_result[i] + '"' +
                        ' required="required"/> <a href="#" data-toggle="modal" data-placement="bottom"> 详细安排 </a> <button class="btn-xs btn-danger"> 删除 </button>'
                }

                if (procedure_result != '') {
                    $("#procedure").find('input,a,button').remove();
                    $("#procedure").append(procedure_keywords_input);
                }
                if (evaluation_result != '') {
                    $("#evaluate").find('input,a,button').remove();
                    $("#evaluate").append(evaluation_keywords_input);
                }
                $('[data-toggle="tooltip"]').tooltip();
                $('[data-toggle="modal"]').tooltip();
                target_content = procedure_content;
                eva_content = evaluation_content;

            }
        });
    }
    else     swal({title:"您未拥有该课程！",type:"warning"});


}



// 文本框中显示详细内容
$(function () {

    $(".target").on("click", "a", function () {
        if (target_content) {
            index = parseInt($(this).index() / 3);
            $('textarea', '#myModal').empty();
            $('textarea', '#myModal').append(target_content[index]);
        }
    });

    $(".evaluation").on("click", "a", function () {
        index = parseInt($(this).index() / 3);
        if (eva_content[index]) {
            $('textarea', '#myEvaModal').empty();
            $('textarea', '#myEvaModal').append(eva_content[index]);
        }
    });
})


$(document).ready(function () {
    // findCourseNameById();
    findById();
    console.log(courseName);
    //提交文本框内容到表格
    $(function () {

        $("#submit1").click(function () {
            let run = false;
            let index = 0;
            Total();
            for (i in target_numArr) {
                if (!target_numArr[i].match(/^[ ]*$/))
                    index++;
                if (index === target_numArr.length)
                    run = true;
            }
            if (run === false)

                swal({title:"输入框不能为空",type:"warning"});
            else {
                //删除后添加
                $.ajax({
                    url: '/target/deleteTargetContent',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        "courseId": courseId
                    },
                    success:function (){
                        let txt1 = $("#procedure").find(":text"); // 获取所有文本框
                        for (let i = 0; i < txt1.length; i++) {
                            console.log(txt1.eq(i).val());
                            console.log(target_content[i]);
                            $.ajax({
                                url: '/target/updateTargetContent',
                                type: 'post',
                                dataType: 'json',
                                data: {
                                    "courseId": courseId,
                                    "courseTarget": txt1.eq(i).val(),
                                    "courseTargetContent": target_content[i]
                                }, success: function () {
                                    //findById();
                                }
                            })
                        }
                    }
                })
                $.ajax({
                    url: '/method/updateTargetById',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        "courseId": courseId,
                        "teacheWay": target_numArr.toString(),
                    },
                    success: function () {
                        swal({title:"提交成功！",type:"success"});
                        findById();
                    }
                });
            }
        });
        $("#submit2").click(function () {
            let run = false;
            let index = 0;
            Total();
            for (i in eva_numArr) {
                if (!eva_numArr[i].match(/^[ ]*$/))
                    index++;
                if (index === eva_numArr.length)
                    run = true;
            }
            if (run === false)
                swal({title:"输入框不能为空",type:"warning"});
            else {

                $.ajax({
                    url: '/target/deleteEvaluationContent',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        "courseId": courseId
                    },
                    success:function (){
                        let txt2 = $("#evaluate").find(":text"); // 获取所有文本框
                        for (let i = 0; i < txt2.length; i++) {
                            console.log(txt2.eq(i).val());
                            console.log(eva_content[i]);
                            $.ajax({
                                url: '/target/updateEvaluationContent',
                                type: 'post',
                                dataType: 'json',
                                data: {
                                    "courseId": courseId,
                                    "courseTarget": txt2.eq(i).val(),
                                    "courseTargetContent": eva_content[i]
                                }, success: function () {
                                    //findById();
                                }
                            })
                        }
                    }
                })
                $.ajax({
                    url: '/method/updateEvaluationById',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        "courseId": courseId,
                        "evaluaKeywords": eva_numArr.toString(),
                    },
                    success: function () {
                        swal({title:"提交成功！",type:"success"});
                        findById();
                    }
                });
            }
        });
    })
})